# encoding=utf-8
from storages.cache import cache
from constant.const import const

r = cache().cache


# 返回1就说明锁着了 ,0就是还没锁着
def lock(id):
    load = """
        local key = KEYS[1]
        local local_key = ARGV[1]
        if redis.call("exists", local_key) == 0 then
            redis.call("set", local_key, 1)
            return 1
        else
            return 0
        end
    """
    is_lock = r.eval(load, 1, const.book_cache, id)
    return is_lock
    # if is_lock == 1:
    #     print("ok")


# 返回1就说明删除锁 ,0就是还没删除锁
def unlock(id):
    unlock = """
        local key = KEYS[1]
        local value = ARGV[1]
        if redis.call("get", key) == value then
            redis.call("del", key)
            return 1
        else
            return 0
        end
    """
    get = str(r.get(id), encoding = 'utf-8')
    r.eval(unlock, 1, id, get)

# if __name__ == "__main__":
#     main()
